<template>
  <el-dialog :modal="false" title="导入收货地址" :close-on-click-modal="false" :visible.sync="visible"
    width="38%">
    <span v-for="(note, i) in isEn() ? notesEn : notes" :key="note"> <span v-html="note"></span> <br v-if="i < notes.length - 1" /></span>
    <el-button style="margin-left: 10px" size="small" type="text" @click="downloadModel">{{
    $t("product.downloadTemplate") }}</el-button>
    <el-upload class="upload-demo" ref="upload" :action="$http.adornUrl('/poiPlatForm/importPoi')"
      :headers="{
    Authorization: $cookie.get('Authorization_vp'),
    locale: lang,
  }" :limit="1" name="excelFile" :on-preview="handlePreview" :on-remove="handleRemove" :on-error="uploadFalse"
      :on-success="uploadSuccess" :file-list="files" :auto-upload="false" :before-upload="beforeAvatarUpload">
      <el-button slot="trigger" size="small" type="success">{{
    $t("product.selectFile")
  }}</el-button>
      <el-button style="margin-left: 10px" size="small" type="primary" @click="submitUpload">{{
    $t("components.confirmUpload") }}</el-button>
    </el-upload>
  </el-dialog>
</template>
<script>
export default {
  data() {
    return {
      visible: false,
      lang: localStorage.getItem("o2oLang") || "zh_CN",
      files: [],
      dataForm: {},
      dataRule: {},
      notes: [
        "注意：",
        "   1、请勿修改表格中的字段顺序，或随意增加、删除表格字段，上传模版大小不能超过10MB，超过应该分批导入;",
        `   2、所属位置需按照《配送地址管理》的数据进行填写，格式: "T1-安检区内-国内"`,
        "   3、上传模版大小不能超过10MB，超过应该分批导入;",
      ],
      notesEn: [
        " Note: ",
        "   1、请勿修改表格中的字段顺序，或随意增加、删除表格字段，上传模版大小不能超过10MB，超过应该分批导入;",
        `   2、所属位置需按照《配送地址管理》的数据进行填写，格式: "T1-安检区内-国内"`,
        "   3、上传模版大小不能超过10MB，超过应该分批导入;",
      ],
    };
  },
  methods: {
    uploadSuccess(response) {
      let res = response.data
      this.files = [];
      this.visible = false;
      this.$emit("refreshDataList");
      if (!res.success){
        this.$message.error(res.msg);
        return
      }
      if (res.key) {
        this.$confirm(res.msg, '提示', {
          confirmButtonText: '下载失败结果',
          cancelButtonText: '取消',
          closeOnClickModal:false,
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/poiPlatForm/importPoiModelError?key=' + res.key),
            method: 'get',
            responseType: "blob", // 解决文件下载乱码问题
          }).then(({ data }) => {
            var blob = new Blob([data], {
              type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
            });
            const fileName = this.isEn()
              ? "ImportErrorResult.xlsx"
              : "收货地址导入失败结果.xlsx";
            const elink = document.createElement("a");
            if ("download" in elink) {
              // 非IE下载
              elink.download = fileName;
              elink.style.display = "none";
              elink.href = URL.createObjectURL(blob);
              document.body.appendChild(elink);
              elink.click();
              URL.revokeObjectURL(elink.href); // 释放URL 对象
              document.body.removeChild(elink);
            } else {
              // IE10+下载
              navigator.msSaveBlob(blob, fileName);
            }
          })
        })
      } else {
        this.$message.success(res.msg);
      }



      // if (response) {
      //   alert(response)
      //   this.files = []
      //   this.visible = false
      //   this.$emit('refreshDataList')
      // } else {
      //   alert(this.isEn() ? 'File import failed' : '文件导入失败')
      // }
    },
    uploadFalse(response) {
      alert(this.isEn() ? "File upload failed!" : "文件上传失败！");
    },
    init(id) {
      this.visible = true;
      this.$nextTick(() => {
        // this.$refs['dataForm'].resetFields()
      });
    },
    // 上传前对文件的大小的判断
    beforeAvatarUpload(file) {
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!extension && !extension2) {
        alert(
          this.isEn()
            ? "Upload template can only be in xls, xlsx format!"
            : "上传模板只能是 xls、xlsx格式!"
        );
      }
      if (!isLt2M) {
        alert(
          this.isEn()
            ? "Upload template size cannot exceed 10MB"
            : "上传模板大小不能超过 10MB!"
        );
      }
      return extension || (extension2 && isLt2M);
    },
    submitUpload() {
      // if (this.businessType != null) {
      // 触发组件的action
      if (!this.$refs.upload.uploadFiles.length) {
        this.$message.error(this.$i18n.t("order.uploadInvoiceTip"));
      }
      this.$refs.upload.submit();
      // }
      // if (this.businessType == null) {
      //   this.businessType = 'businessType不能为空'
      // }
    },
    handleRemove(file) {
      // console.log(file)
    },
    handlePreview(file) {
      if (file.response.status) {
        alert(this.isEn() ? "This file import success" : "此文件导入成功");
      } else {
        alert(this.isEn() ? "This file import failed" : "此文件导入失败");
      }
    },
    // 下载模板
    downloadModel() {
      this.$http({
        url: this.$http.adornUrl("/poiPlatForm/importPoiModel"),
        method: "get",
        responseType: "blob", // 解决文件下载乱码问题
      }).then(({ data }) => {
        var blob = new Blob([data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
        });
        const fileName = this.isEn()
          ? "ImportTemplate.xlsx"
          : "收货地址导入模板.xlsx";
        const elink = document.createElement("a");
        if ("download" in elink) {
          // 非IE下载
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
      });
    },
    isEn() {
      if (this.$i18n.t("language") === "English") {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>
